// content.js - Content Script for intercepting fetch and XMLHttpRequest
class ContentInterceptor {
  constructor() {
    this.rules = new Map();
    this.logs = [];
    this.requestRecords = new Map();
    this.init();
  }

  async init() {
    // 获取拦截规则
    await this.loadRules();
    
    // 注入更深层的拦截脚本
    this.injectScript();
    
    // 监听来自inject script和background的事件
    this.setupEventListeners();
    
    // 监听规则更新
    this.setupRuleUpdateListener();
    
    // 定期同步规则
    setInterval(() => this.syncRulesToInjectScript(), 2000);
  }

  async loadRules() {
    try {
      const response = await chrome.runtime.sendMessage({ type: 'GET_RULES' });
      if (response.success) {
        this.rules = new Map(Object.entries(response.data));
      }
    } catch (error) {
      // Service Worker可能未就绪，忽略此错误
    }
  }

  injectScript() {
    try {
      const script = document.createElement('script');
      script.src = chrome.runtime.getURL('inject.js');
      script.onload = function() {
        this.remove();
      };
      (document.head || document.documentElement).appendChild(script);
    } catch (error) {
      // 静默处理注入失败
    }
  }

  async syncRulesToInjectScript() {
    // 将规则同步到注入的脚本
    document.dispatchEvent(new CustomEvent('mockRulesUpdated', {
      detail: { rules: Object.fromEntries(this.rules) }
    }));
  }

  setupEventListeners() {
    // 监听来自inject script的规则请求
    document.addEventListener('getMockRules', () => {
      this.syncRulesToInjectScript();
    });

    // 监听来自inject script的日志
    document.addEventListener('apiMockLog', (event) => {
      this.handleRequestLog(event.detail);
    });

    // 监听来自inject script的请求记录
    document.addEventListener('apiRequestRecord', (event) => {
      this.handleRequestRecord(event.detail);
    });

    // 监听来自background script的响应修改事件
    document.addEventListener('apiMockResponse', (event) => {
      this.handleMockResponse(event.detail);
    });
  }

  setupRuleUpdateListener() {
    // 监听来自popup的规则更新消息
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      if (message.type === 'RULES_UPDATED') {
        this.loadRules().then(() => {
          this.syncRulesToInjectScript();
        });
      } else if (message.type === 'GET_REQUEST_RECORDS') {
        // 返回当前页面的请求记录
        sendResponse({
          success: true,
          data: Object.fromEntries(this.requestRecords)
        });
      }
      
      return true; // 保持消息通道打开
    });
  }

  handleRequestLog(logData) {
    // 处理来自inject script的请求日志
    this.logs.push(logData);
    
    // 只保留最近100条日志
    if (this.logs.length > 100) {
      this.logs = this.logs.slice(-100);
    }
  }

  handleRequestRecord(recordData) {
    // 处理来自inject script的请求记录
    const requestId = Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    
    const requestRecord = {
      id: requestId,
      url: recordData.url,
      method: recordData.method || 'GET',
      requestHeaders: recordData.requestHeaders,
      requestBody: recordData.requestBody,
      responseHeaders: recordData.responseHeaders,
      responseBody: recordData.responseBody,
      status: recordData.status || 200,
      timestamp: Date.now()
    };

    this.requestRecords.set(requestId, requestRecord);
    
    // 只保留最近50个请求记录
    if (this.requestRecords.size > 50) {
      const firstKey = this.requestRecords.keys().next().value;
      this.requestRecords.delete(firstKey);
    }

    // 通知background script有新的请求记录
    chrome.runtime.sendMessage({
      type: 'NEW_REQUEST_RECORD',
      record: requestRecord
    }).catch(() => {
      // 静默处理发送失败
    });
  }

  handleMockResponse(detail) {
    // 处理来自background script的响应修改
    // 将响应修改信息传递给inject script
    document.dispatchEvent(new CustomEvent('mockResponseReady', {
      detail: detail
    }));
  }
}

// 启动内容拦截器
const contentInterceptor = new ContentInterceptor();